import { resolve, basename } from 'path'

import ts from 'rollup-plugin-typescript2'
import json from '@rollup/plugin-json'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'

const packagesFormats = process.env.FORMATS && process.env.FORMATS.split(',')
const sourcemap = process.env.SOURCE_MAP

// 根据target找到打包的目录
const packageDir = resolve(__dirname, 'packages', process.env.TARGET)
const absolutePath = path => resolve(packageDir, path)
const fileName = basename(packageDir)
const pkg = require(absolutePath('package.json'))

const outputConfig = {
  'esm-bundler': {
    file: absolutePath(`dist/${fileName}.esm-bundler.js`),
    format: 'es'
  },
  'cjs': {
    file: absolutePath(`dist/${fileName}.cjs.js`),
    format: 'cjs'
  },
  'global': {
    file: absolutePath(`dist/${fileName}.global.js`),
    format: 'iife'
  }
}

// 打包所有文件的时候可能不会传递packagesFormats这个值
const packageConfigs = packagesFormats.length ? packagesFormats : pkg.buildOptions.formats

const createConfig = (format, output) => {
  output.sourcemap = sourcemap
  output.exports = 'named'
  let external = [] // 外部模块 哪些模块不需要打包
  if (format === 'global') {
    output.name = pkg.buildOptions.name
  } else {
    external = [...Object.keys(pkg.dependencies)]
  }
  return {
    input: absolutePath('src/index.ts'),
    output,
    external,
    plugins: [
      json(),
      ts(),
      commonjs(),
      nodeResolve()
    ]
  }
}
export default packageConfigs.map(format => createConfig(format, outputConfig[format]))